﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Secair.Core.Tool
{
    public class GBCheck
    {
        #region CS校验
        /// <summary>
        /// CS校验
        /// </summary>
        /// <param name="data">待校验Byte数组</param>
        /// <returns>CS校验值</returns>
        public static byte CS(byte[] data)
        {
            byte cs = 0;
            for (int i = 0; i < data.Length; i++)
            {
                cs = (byte)((cs + data[i]) % 256);
            }
            return cs;
        }
        #endregion

        #region BBC
        /// <summary>
        /// BBC校验
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static String GetBCC(byte[] data)
        {
            String ret = "";
            byte[] BCC = new byte[1];
            for (int i = 0; i < data.Length; i++)
            {
                BCC[0] = (byte)(BCC[0] ^ data[i]);
            }
            String hex = (BCC[0] & 0xFF).ToString("X");

            if (hex.Length == 1)
            {
                hex = '0' + hex;
            }
            ret += hex.ToUpper();
            return ret;
        }
        #endregion

        #region LRC和校验
        /// <summary>
        /// LRC和校验
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte LRC(byte[] data)
        {
            byte lrc = 0;
            foreach (byte c in data)
            {
                lrc += c;
            }
            return (byte)-lrc;
        }
        #endregion
    }
}
